#define _CRT_SECURE_NO_WARNINGS 1

//https://leetcode.cn/problems/pacific-atlantic-water-flow/

class Solution {
    vector<vector<bool>> checkPacific;
    vector<vector<bool>> checkAtlantic;
    int m, n;
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
public:
    vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) {
        m = heights.size(), n = heights[0].size();
        checkAtlantic.resize(m, vector<bool>(n));
        checkPacific.resize(m, vector<bool>(n));
        //pac
        for (int i = 0; i < m; i++) dfs(heights, i, 0, checkPacific);
        for (int j = 0; j < n; j++) dfs(heights, 0, j, checkPacific);
        //atl
        for (int i = 0; i < m; i++) dfs(heights, i, n - 1, checkAtlantic);
        for (int j = 0; j < n; j++) dfs(heights, m - 1, j, checkAtlantic);

        vector<vector<int>> ret;
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
            {
                if (checkAtlantic[i][j] && checkPacific[i][j]) ret.push_back({ i,j });
            }

        return ret;
    }

    void dfs(vector<vector<int>>& heights, int i, int j, vector<vector<bool>>& check)
    {
        check[i][j] = true;
        for (int z = 0; z < 4; z++)
        {
            int x = i + dx[z], y = j + dy[z];
            if (x >= 0 && x < m && y >= 0 && y < n && !check[x][y] && heights[i][j] <= heights[x][y])
            {
                dfs(heights, x, y, check);
            }
        }
    }
};